package db.swing1;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableModel;

import de.dnb.basics.applicationComponents.DbUtils;

public class ExecuteSqlActionListener implements ActionListener {
	private static final String ROW_COUNT_TEXT = "Row count: ";
	private final JTextField sqlCommandTextField;
	private final JTextField sqlInfoTextField;
	private final JTable table;
	private final PreparedStatement preparedStatement;
	ResultSet currentResultSet = null;

	public ExecuteSqlActionListener(final JTextField sqlCommandTextField,
			final JTextField sqlInfoTextField, final JTable table,
			final PreparedStatement statement) {
		this.sqlCommandTextField = sqlCommandTextField;
		this.sqlInfoTextField = sqlInfoTextField;
		this.table = table;
		this.preparedStatement = statement;
	}

	@Override
	public void actionPerformed(final ActionEvent event) {
		final String searchTerm = sqlCommandTextField.getText();
		try {
			// ResultSet freigeben, falls bereits eins belegt war
			DbUtils.safeCloseResultSet(currentResultSet);
			preparedStatement.setString(1, searchTerm + '%');
			currentResultSet = preparedStatement.executeQuery();
			final TableModel tableModel =
					new ResultSetTableModel(currentResultSet);
			table.setModel(tableModel);
			sqlInfoTextField.setText(ROW_COUNT_TEXT + tableModel.getRowCount());
		} catch (final SQLException e1) {
			sqlInfoTextField.setText(e1.getLocalizedMessage());
		}
	}
}